<template>
    <div class="app-container">
      <el-card class="box-card">
        <!-- 使用 ref 注册 el-form -->
        <el-form :model="form" label-width="120px" ref="formRef" status-icon>
          <!-- 旧密码 -->
          <el-form-item label="旧密码" 
          :label-width="labelWidth" 
          prop="oldPassword" 
          :rules="[
            { required: true, message: '旧密码不能为空', trigger: 'blur' }
            ]"
            >
            <el-input
              v-model="form.oldPassword"
              type="password"
              placeholder="请输旧密码"
            />
          </el-form-item>
  
          <!-- 新密码 -->
          <el-form-item label="新密码" :label-width="labelWidth" prop="newPassword" 
          :rules="[
                { required: true, message: '新密码不能为空', trigger: 'blur' },
                { min: 3, message: '密码长度不能少于 6 位', trigger: 'blur' }
              ]"
              >
            <el-input
              v-model="form.newPassword"
              type="password"
              placeholder="请输入新密码"

            />
          </el-form-item>
  
          <!-- 确认新密码 -->
          <el-form-item label="确认密码" :label-width="labelWidth" prop="confirmPassword"        
          :rules="[
                { required: true, message: '确认密码不能为空', trigger: 'blur' },
                { validator: checkConfirmPassword, trigger: 'blur' }
              ]"
              >
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请确认新密码"
            />
          </el-form-item>
  
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  
  // 表单数据
  const form = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  
  const labelWidth = '120px';
  
  // 引用表单
  const formRef = ref(null);
  
  // 确认密码校验
  const checkConfirmPassword = (rule, value, callback) => {
    if (value !== form.value.newPassword) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  };
  
  // 提交表单
  const submitForm = () => {
    const formInstance = formRef.value;
    formInstance.validate((valid) => {
      if (valid) {
        // 调用修改密码的请求
        changePassword();
      } else {
        console.log('表单验证失败');
        return false;
      }
    });
  };
  
  // 重置表单
  const resetForm = () => {
    form.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    };
  };


// 修改密码函数
const changePassword = async () => {
  const data = {
    oldPassword: form.value.oldPassword,
    newPassword: form.value.newPassword
  };

  try {
    // 使用 await 等待 axios 请求完成
    const response = await axios.patch('user/change_password/', data);
    console.log('response is:',response)
    // 假设后端返回 { code: 200, msg: "密码修改成功" }
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '密码修改成功');
      resetForm(); // 清空表单
    } else if (response.data.code === 400) {
      ElMessage.error(response.data.msg || '密码修改失败');
    } else {
      ElMessage.error(response.data.msg || '密码修改失败');
    }
  } catch (error) {
    // 捕获异常
    console.log('修改密码失败:', error);

    // 如果是 axios 请求失败，打印请求错误信息
    if (error.response) {
      // 服务器响应错误
      ElMessage.error(`服务器错误: ${error.response.status}`);
    } else if (error.request) {
      // 请求已发送但没有收到响应
      ElMessage.error('请求超时或没有响应');
    } else {
      // 其他错误
      ElMessage.error('发生未知错误');
    }
  }
};

  </script>
  
  <style scoped>
  .app-container {
    height: 100%;
    background-color: #f9f9f9;
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .box-card{
    height: 100%;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .card-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-input {
    width: 100%;
  }
  
  .el-button {
    margin-right: 10px;
  }
  </style>
  